<template>
  <div>
    <van-search v-model="value" show-action :placeholder="type | placeholder" @input="remote" @search="onSearch" @cancel="backPage" @clear="onClear" />
    <div v-show="!isList" class="search-house-scroll">
      <search-history ref="history" :type="type" :val.sync="value" />
      <search-hot :type="type" />
    </div>
    <div v-show="isList">
      <div v-if="list && list.length" class="search-result">
        <house-card v-for="item in list" :key="item.id" :title="item.title" :total-price="item.totalPrice" :average-price="item.averagePrice" @click.native="toDetail(item)" />
      </div>
      <van-empty v-else image="search" description="未查询到相关数据" />
    </div>
  </div>
</template>

<script>
import { Search, Empty } from 'vant'
import SearchHistory from './SearchHistory'
import SearchHot from './SearchHot'
import { getHomeList } from '@/api/home/index'
import HouseCard from '@/components/Card/HouseCard'

export default {
  components: {
    [Search.name]: Search,
    [Empty.name]: Empty,
    SearchHistory,
    SearchHot,
    HouseCard
  },
  filters: {
    placeholder(type) {
      const typeMap = {
        '1': '请输入楼盘名、小区名或地址',
        '2': '请输入楼盘名或地址',
        '3': '请输入小区名或地址',
        '4': '请输入商铺名',
        '5': '请输入装修公司名'
      }
      return typeMap[type]
    }
  },
  props: {
    type: {
      type: [String],
      default() {
        return '1'
      }
    }
  },
  data() {
    return {
      value: '',
      isList: false,
      list: []
    }
  },
  methods: {
    async remote(val) {
      if (val) {
        const {
          data: { records }
        } = await getHomeList({ type: this.type, title: val, page: 1, limit: 20 })
        this.list = records
        this.isList = true
      } else {
        this.isList = false
        this.list = []
      }
    },
    onSearch(val) {
      this.$nextTick(() => {
        this.$refs.history.$emit('setHistory', val)
        this.value = ''
        this.isList = false
        this.list = []
        this.$router.push({ name: 'HouseList', query: { name: val, type: this.type } })
      })
    },
    onClear() {
      this.value = ''
      this.isList = false
      this.list = []
    },
    toDetail(item) {
      this.$nextTick(() => {
        this.$refs.history.$emit('setHistory', item.title)
        this.$router.push({ name: 'HouseDetail', query: { id: item.id } })
      })
    }
  }
}
</script>

<style scoped lang="less"></style>
